package com.woniu.order.service.consumer;

import com.woniu.order.infra.model.OrderLog;
import com.woniu.order.service.OrderLogService;
import com.woniu.order.service.dto.CancelOrderDto;
import com.woniu.order.common.enums.OrderStatusEnum;
import com.woniu.order.infra.model.Order;
import com.woniu.order.service.OrderService;
import com.woniu.order.service.param.OrderEntryServiceParam;
import com.woniu.product.client.ProductManageClient;
import com.woniu.product.client.param.RestoreStockParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 回查取消订单的消费
 *
 * @author Administrator
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = "lxlg-order-cancel", consumerGroup = "lxlg-order-cancel")
public class CancelOrderConsuer implements RocketMQListener<CancelOrderDto> {

    @Resource
    private OrderService orderService;

    @Resource
    private ProductManageClient productManageClient;

    @Resource
    private OrderLogService orderLogService;

    /**
     * 检查当前订单的支付情况
     *
     * @param message
     */
    @Override
    public void onMessage(CancelOrderDto message) {
        log.info("============开始检查当前订单的支付情况===========");
        Order order = orderService.getById(message.getOrderId());
        if (order.getOrderState().equals(OrderStatusEnum.CREATED.getCode())) {
            order.setOrderState(OrderStatusEnum.CANCEL.getCode());
            orderService.updateById(order);
            //还原库存
            for (OrderEntryServiceParam o : message.getOrderEntryServiceParams()) {
                Integer productId = o.getSkuId();
                Integer quantity = o.getQuantity();
                RestoreStockParam restoreStockParam = new RestoreStockParam();
                restoreStockParam.setProductId(productId);
                restoreStockParam.setQuantity(quantity);
                //扣减销量
                productManageClient.subtractSkuSalesCount(productId, quantity);
                try {
                    productManageClient.restoreStock(restoreStockParam);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
            //记录订单日志
            OrderLog orderLog = new OrderLog();
            orderLog.setUserId(order.getUserId());
            orderLog.setOrderId(order.getOrderId());
            orderLog.setOrderNum(order.getOrderNum());
            orderLog.setOrderContent("取消订单");
            orderLog.setLogTime(new Date());
            orderLogService.save(orderLog);
            log.info("============退单执行结束===========");
        } else
            log.info("============发现订单已经支付，不做处理===========");
    }
} 
